/*
 *  University Of Canterbury - Department of Electrical and Computer Engineering
 *
 *  ENEL323 - Software Engineering 1
 *  Assignment 2: Real-time collision avoidance and anti-locking brake system
 *  File: circular_buffer.c
 *
 *  Circular Buffer module.
 *
 *  Authors: Nick Hartley (nijh119) and Andrew Nicholas(adn26)
 *  Last Updated: 22 September 2010
 *
 */

#include "circular_buffer.h"


void BUFFER_initialisation (dc_buffer_t *buffer ){

	buffer->currentptr1 = &(buffer->buffer1[0]); 
        buffer->isfull1 = false;

	buffer->currentptr2 = &(buffer->buffer2[0]); 
        buffer->isfull2 = false;
	
	buffer->read_buffer = BUFFER1;
	buffer->write_buffer = BUFFER1;
}

uint8_t write (dc_buffer_t *buffer, uint16_t value)
{	
	if (buffer->isfull1 == false && buffer->write_buffer == BUFFER1) 
	{	
		*(buffer->currentptr1) = value; //Write value to buffer pointer
		
		if (buffer->currentptr1 == &(buffer->buffer1[BUFFER_LENGTH -1])) 
		{
		//	puts("buffer1 is now full"); //Display terminal message
			buffer->isfull1 = true;
			buffer->currentptr1 = &(buffer->buffer1[START_OF_BUFFER]);
			buffer->write_buffer = BUFFER2;
			return 1;
				
		}
		else buffer->currentptr1++ ; //Shift buffer pointer onto next position to write to
		
	} 
	else if (buffer->isfull2 == false && buffer->write_buffer == BUFFER2) //Write to buffer2
	{
		*(buffer->currentptr2) = value; //Write value to buffer pointer
		if (buffer->currentptr2 == &(buffer->buffer2[BUFFER_LENGTH -1])) 
		{	
			//puts("buffer2 is now full"); //Display terminal message
			buffer->isfull2 = true;
			buffer->currentptr2 = &(buffer->buffer2[START_OF_BUFFER]);
			buffer->write_buffer = BUFFER1;
			return 1;
		}
		else buffer->currentptr2++;  //Shift buffer pointer onto next position to write to 
	
	} 
	return 0;
}


uint16_t read (dc_buffer_t *buffer ) 
{
	uint16_t value = 0;

	if (buffer->isfull1 == true && buffer->read_buffer == BUFFER1)  //If full then read
	{
		value = *buffer->currentptr1;
		
		if (buffer->currentptr1 == &buffer->buffer1[BUFFER_LENGTH - 1]) 
		{
			buffer->currentptr1 = &buffer->buffer1[START_OF_BUFFER]; //Set to start of buffer
			buffer->isfull1 = false; //Indicate that buffer has been read and is now 'empty'
			buffer->read_buffer = BUFFER2;
			//puts("buffer1 has now been read"); //Display terminal message
		}
		else buffer->currentptr1++ ; //Shift buffer pointer onto next position to write to		
		
	} 
	else if(buffer->isfull2 == true && buffer->read_buffer == BUFFER2) //Read buffer2
	{
		value = *buffer->currentptr2;
		
		if (buffer->currentptr2 == &buffer->buffer2[BUFFER_LENGTH - 1]) 
		{
			buffer->currentptr2 = &buffer->buffer2[START_OF_BUFFER]; //Set to start of buffer
			buffer->isfull2 = false; //Indicate that buffer has been read and is now 'empty'
			buffer->read_buffer = BUFFER1;
			//puts("buffer2 has now been read"); //Display terminal message
		}
		else buffer->currentptr2++; //Shift buffer pointer onto next position to write to 
	} 
	return value;
}

